package com.new1cloud.upload.server.service.bootstrap.handler;

import com.new1cloud.file.config.UploadConfig;
import com.new1cloud.file.domain.FileUploadBasicInfo;
import com.new1cloud.file.domain.FileUploadProcess;
import com.new1cloud.upload.server.service.FileUploadService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 处理{@link FileUploadBasicInfo}类型消息的Handler
 */
public class FileUploadBasicInfoHandler extends ChannelInboundHandlerAdapter {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    private final FileUploadService fileUploadService;

    public FileUploadBasicInfoHandler(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FileUploadBasicInfo) {
            log.info("收到来自客户端发送的FileUploadBasicInfo信息.");
            FileUploadBasicInfo basicInfo = (FileUploadBasicInfo) msg;
            //检查该文件的上传进度情况(一般是不会返回NULL)
            FileUploadProcess fileUploadProcess = fileUploadService.checkUploadProcess(basicInfo.getFileHash(), basicInfo.getFileSize(),
                    basicInfo.getFileName(), basicInfo.getUploadPath());
            if(Objects.isNull(fileUploadProcess)) {
                //fileSize为-1表示服务端未查询到上传进度信息
                fileUploadProcess = new FileUploadProcess(basicInfo.getFileName(), -1L, basicInfo.getFileHash(), 0, null,
                        UploadConfig.getChunkSize(), "");
            }
            ctx.writeAndFlush(fileUploadProcess);
        } else {
            log.error("服务端[FileUploadBasicInfoHandler]收到非预期类型的消息:{},将被丢弃!", msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        log.error("服务端发生异常[FileUploadBasicInfoHandler]: ", cause);
        ctx.close();
    }
}
